import React, { Component } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import ScrollSelect from '@/components/ScrollSelect';
import IconButton from '@/components/IconButton';
import { Row, Col, Form, Input, Select, Card, Button, DatePicker } from 'antd';

import { connect } from 'dva';
import api from '@/api';
import get from 'lodash/get';
import moment from 'moment';
import isEmpty from 'lodash/isEmpty';

import styles from './Income.less';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

@Form.create()
@connect(({ loading }) => ({ loading: loading.effects['dashboard/queryIncome'] }))
class Income extends Component {
  state = {
    incomeList: {
      list: [],
      pagination: {},
    },
    searchParams: {},
  };
  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
      width: 100,
    },
    {
      title: '订单号',
      dataIndex: 'waybillNo',
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatusName',
    },
    {
      title: '订单日期',
      dataIndex: 'createTime',
    },
    {
      title: '客户',
      dataIndex: 'customerName',
    },
    {
      title: '产品',
      dataIndex: 'productName',
    },
    {
      title: '总计金额(CNY)',
      dataIndex: 'saleTotal',
      align: 'right',
    },
    {
      title: '揽收费计费金额(CNY)',
      dataIndex: 'salePUCFee',
      align: 'right',
    },
    {
      title: '空运费计费金额(CNY)',
      dataIndex: 'saleAFCFee',
      align: 'right',
    },
    {
      title: '提货费计费金额(CNY)',
      dataIndex: 'salePPCFee',
      align: 'right',
    },
    {
      title: '配送费计费金额(CNY)',
      dataIndex: 'saleDEFFee',
      align: 'right',
    },
    {
      title: '保障服务计费金额(CNY)',
      dataIndex: 'insAmount',
      align: 'right',
    },
    {
      title: '喜鹊豆抵扣金额(CNY)',
      dataIndex: 'beanDisAmount',
      align: 'right',
    },
    {
      title: '现金券抵扣金额(CNY)',
      dataIndex: 'cashDisAmount',
      align: 'right',
    },
    {
      title: '平台促销优惠金额(CNY)',
      dataIndex: 'proDisAmount',
      align: 'right',
    },
    {
      title: '会员优惠金额(CNY)',
      dataIndex: 'memberDisAmount',
      align: 'right',
    },
    {
      title: '保障服务费抵扣金额(CNY)',
      dataIndex: 'insDisAmount',
      align: 'right',
    },
    {
      title: '实收总金额(CNY)',
      dataIndex: 'actualAmount',
      align: 'right',
    },
    {
      title: '揽收费实收金额(CNY)',
      dataIndex: 'saleActualPUCFee',
      align: 'right',
    },
    {
      title: '空运费实收金额(CNY)',
      dataIndex: 'saleActualAFCFee',
      align: 'right',
    },
    {
      title: '提货费实收金额(CNY)',
      dataIndex: 'saleActualPPCFee',
      align: 'right',
    },
    {
      title: '配送费实收金额(CNY)',
      dataIndex: 'saleActualDEFFee',
      align: 'right',
    },
    {
      title: '保障服务费(CNY)',
      dataIndex: 'insActualAmount',
      align: 'right',
    },
    {
      title: '',
      width: '3%',
    },
    {
      title: '始发地',
      dataIndex: 'startPlace',
    },
    {
      title: '目的地',
      dataIndex: 'endPlace',
    },
    {
      title: '货物类型',
      dataIndex: 'cargoTypeName',
    },
    {
      title: '应收核销状态',
      dataIndex: 'isVerified',
      render: text => {
        return text ? '已核销' : '未核销';
      },
    },
    {
      title: '计费重量(kg)',
      dataIndex: 'feeWeight',
    },
    {
      title: '件数',
      dataIndex: 'packageNum',
    },
    {
      title: '结算方式',
      dataIndex: 'settlementTypeCodeName',
    },
    {
      title: '核销日期',
      dataIndex: 'verifiedDate',
    },
    {
      title: '完成时间',
      dataIndex: 'finishedTime',
    },
  ];
  calcIndex = index => {
    const { incomeList } = this.state;
    let currentPage = get(incomeList, 'pagination.currentPage') || 1;
    let pageSize = get(incomeList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };
  componentDidMount() {
    this.queryIncome();
  }
  queryIncome = ({ pageIndex = 1, pageSize = 50 } = {}) => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    validateFields((err, value) => {
      let params = {
        isVerified: value.isVerified,
        waybillNos: value.waybillNos,
        pageIndex,
        pageSize,
      };
      if (value.customerId) {
        params = { ...params, customerId: value.customerId.key };
      }
      if (value.date && value.date.length === 2) {
        params = {
          ...params,
          startTime: value.date[0].startOf('day').format('YYYY-MM-DD 00:00:00'),
          endTime: value.date[1].startOf('day').format('YYYY-MM-DD 23:59:59'),
        };
      }
      if (value.refId) {
        params = { ...params, productId: value.refId.key };
      }
      dispatch({
        type: 'dashboard/queryIncome',
        payload: {
          queryParams: params,
        },
      }).then(({ errorCode, data, pagination }) => {
        if (errorCode === 0) {
          this.setState({ incomeList: { list: data, pagination }, searchParams: params });
        }
      });
    });
  };
  handleTableChange = pagination => {
    let params = { pageIndex: pagination.current, pageSize: pagination.pageSize };
    this.queryIncome(params);
  };

  handleReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.queryIncome();
  };
  queryCustomers = params => {
    return api.customer.shortQuery({
      queryParams: params,
    });
  };
  // 搜索栏获取产品
  queryProducts = params => {
    return api.product.query({
      queryParams: params,
    });
  };
  // 搜索栏获取服务
  queryServices = params => {
    return api.service.query({
      queryParams: params,
    });
  };
  render() {
    const {
      form: { getFieldDecorator },
      loading,
    } = this.props;
    const { incomeList, searchParams } = this.state;
    let exportUrl = '/api/v1/dashBoard/orderSaleAnalysis/down';
    if (!isEmpty(searchParams)) {
      let params = Object.keys(searchParams)
        .filter(item => searchParams[item])
        .map(item => `${item}=${searchParams[item]}`)
        .join('&');
      exportUrl = exportUrl + '?' + params;
    }
    return (
      <PageHeaderWrapper title="收入报表">
        <Card bordered={false}>
          <div className={styles.search}>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="订&ensp;单&ensp;号">
                  {getFieldDecorator('waybillNos')(
                    <Input
                      style={{ width: '100%' }}
                      maxLength={500}
                      placeholder="多个订单号以英文逗号分隔"
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="客&emsp;&emsp;户">
                  {getFieldDecorator('customerId')(
                    <ScrollSelect
                      allowClear
                      search={this.queryCustomers}
                      style={{ width: '100%' }}
                      placeholder="请输入客户名称或编码"
                      optionLabel="name"
                      optionKey="id"
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="核销状态">
                  {getFieldDecorator('isVerified')(
                    <Select style={{ width: '100%' }} allowClear={true}>
                      <Option value={false}>未核销</Option>
                      <Option value={true}>已核销</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="产&emsp;&emsp;品">
                  {getFieldDecorator('refId')(
                    <ScrollSelect
                      allowClear
                      search={this.queryProducts}
                      style={{ width: '100%' }}
                      maxLength={15}
                      placeholder="请输入产品名称或编码"
                      optionKey="id"
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="订单日期">
                  {getFieldDecorator('date', {
                    initialValue: [
                      moment()
                        .startOf('day')
                        .subtract(30, 'days'),
                      moment().endOf('day'),
                    ],
                  })(
                    <RangePicker
                      allowClear={false}
                      style={{ width: '100%' }}
                      format="YYYY-MM-DD"
                      placeholder={['开始日期', '结束日期']}
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <Button onClick={this.handleReset}>重置</Button>
                <Button type="primary" onClick={this.queryIncome}>
                  查询
                </Button>
              </Col>
            </Row>
          </div>
          <div style={{ marginBottom: 20 }}>
            <a href={exportUrl} style={{ color: 'rgba(0, 0, 0, 0.65)' }}>
              <IconButton icon="icon-export" title="导出" />
            </a>
          </div>
          <StandardTable
            rowKey="id"
            loading={loading}
            data={incomeList}
            columns={this.columns}
            onChange={this.handleTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Income;
